using System.Windows;
using System.Windows.Media;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using MaterialDesignThemes.Wpf;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 主题管理服务
    /// </summary>
    public class ThemeService : IThemeService
    {
        private readonly ILogger<ThemeService> _logger;
        private readonly IConfiguration _configuration;
        private readonly PaletteHelper _paletteHelper;

        /// <summary>
        /// 主题变更事件
        /// </summary>
        public event EventHandler<ThemeChangedEventArgs>? ThemeChanged;

        public ThemeService(ILogger<ThemeService> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
            _paletteHelper = new PaletteHelper();
        }

        /// <summary>
        /// 获取当前主题配置
        /// </summary>
        public ThemeConfig GetCurrentTheme()
        {
            try
            {
                var theme = _paletteHelper.GetTheme();

                return new ThemeConfig
                {
                    BaseTheme = theme.GetBaseTheme().ToString(),
                    PrimaryColor = ColorToHex(theme.PrimaryMid.Color),
                    SecondaryColor = ColorToHex(theme.SecondaryMid.Color),
                    BackgroundColor = ColorToHex(theme.Background),
                    SurfaceColor = ColorToHex(theme.CardBackground),
                    TextColor = ColorToHex(theme.Body),
                    AccentColor = ColorToHex(theme.PrimaryLight.Color)
                };
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前主题失败，返回默认主题");
                return new ThemeConfig
                {
                    BaseTheme = "Light",
                    PrimaryColor = "#2196F3",
                    SecondaryColor = "#03DAC6",
                    AccentColor = "#1976D2"
                };
            }
        }

        /// <summary>
        /// 应用主题配置
        /// </summary>
        public async Task ApplyThemeAsync(ThemeConfig themeConfig)
        {
            try
            {
                var theme = _paletteHelper.GetTheme();

                // 设置基础主题
                if (themeConfig.BaseTheme == "Dark")
                {
                    theme.SetBaseTheme(Theme.Dark);
                }
                else
                {
                    theme.SetBaseTheme(Theme.Light);
                }

                // 设置主色调
                if (!string.IsNullOrEmpty(themeConfig.PrimaryColor))
                {
                    var primaryColor = HexToColor(themeConfig.PrimaryColor);
                    theme.SetPrimaryColor(primaryColor);
                }

                // 设置次要色调
                if (!string.IsNullOrEmpty(themeConfig.SecondaryColor))
                {
                    var secondaryColor = HexToColor(themeConfig.SecondaryColor);
                    theme.SetSecondaryColor(secondaryColor);
                }

                // 应用主题
                _paletteHelper.SetTheme(theme);

                // 保存配置
                await SaveThemeConfigAsync(themeConfig);

                // 触发主题变更事件
                ThemeChanged?.Invoke(this, new ThemeChangedEventArgs(themeConfig));

                _logger.LogInformation($"主题已应用: {themeConfig.BaseTheme}, 主色调: {themeConfig.PrimaryColor}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "应用主题时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 获取预设主题列表
        /// </summary>
        public List<PresetTheme> GetPresetThemes()
        {
            return new List<PresetTheme>
            {
                // 浅色主题
                new PresetTheme
                {
                    Name = "浅蓝色（默认）",
                    Description = "清新的浅蓝色主题",
                    BaseTheme = "Light",
                    PrimaryColor = "#2196F3", // 浅蓝色
                    SecondaryColor = "#03DAC6",
                    AccentColor = "#1976D2",
                    Tags = new List<string> { "默认", "蓝色", "清新", "经典" }
                },
                new PresetTheme
                {
                    Name = "深紫色",
                    Description = "优雅的深紫色主题",
                    BaseTheme = "Light",
                    PrimaryColor = "#673AB7",
                    SecondaryColor = "#CDDC39",
                    AccentColor = "#512DA8",
                    Tags = new List<string> { "紫色", "优雅", "高贵" }
                },
                new PresetTheme
                {
                    Name = "绿色自然",
                    Description = "清新的绿色主题",
                    BaseTheme = "Light",
                    PrimaryColor = "#4CAF50",
                    SecondaryColor = "#FF9800",
                    AccentColor = "#388E3C",
                    Tags = new List<string> { "绿色", "自然", "清新", "护眼" }
                },
                new PresetTheme
                {
                    Name = "橙色活力",
                    Description = "充满活力的橙色主题",
                    BaseTheme = "Light",
                    PrimaryColor = "#FF9800",
                    SecondaryColor = "#9C27B0",
                    AccentColor = "#F57C00",
                    Tags = new List<string> { "橙色", "活力", "温暖", "创意" }
                },

                // 暗黑主题系列
                new PresetTheme
                {
                    Name = "经典暗黑",
                    Description = "护眼的经典暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#2196F3",
                    SecondaryColor = "#03DAC6",
                    AccentColor = "#1976D2",
                    Tags = new List<string> { "经典", "护眼", "蓝色", "暗黑", "默认" }
                },
                new PresetTheme
                {
                    Name = "暗夜紫罗兰",
                    Description = "神秘优雅的紫色暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#9C27B0",
                    SecondaryColor = "#CDDC39",
                    AccentColor = "#7B1FA2",
                    Tags = new List<string> { "紫色", "神秘", "优雅", "暗黑", "高贵" }
                },
                new PresetTheme
                {
                    Name = "深海蓝调",
                    Description = "深邃宁静的蓝色暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#1565C0",
                    SecondaryColor = "#00BCD4",
                    AccentColor = "#0D47A1",
                    Tags = new List<string> { "蓝色", "深邃", "宁静", "暗黑", "专业" }
                },
                new PresetTheme
                {
                    Name = "森林暗绿",
                    Description = "自然护眼的绿色暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#2E7D32",
                    SecondaryColor = "#FF6F00",
                    AccentColor = "#1B5E20",
                    Tags = new List<string> { "绿色", "自然", "护眼", "暗黑", "舒适" }
                },
                new PresetTheme
                {
                    Name = "暗红玫瑰",
                    Description = "温暖优雅的红色暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#C62828",
                    SecondaryColor = "#FFC107",
                    AccentColor = "#B71C1C",
                    Tags = new List<string> { "红色", "温暖", "优雅", "暗黑", "浪漫" }
                },
                new PresetTheme
                {
                    Name = "午夜橙光",
                    Description = "活力温暖的橙色暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#E65100",
                    SecondaryColor = "#8BC34A",
                    AccentColor = "#BF360C",
                    Tags = new List<string> { "橙色", "活力", "温暖", "暗黑", "创意" }
                },
                new PresetTheme
                {
                    Name = "极夜青蓝",
                    Description = "冷静专业的青蓝暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#00695C",
                    SecondaryColor = "#FF5722",
                    AccentColor = "#004D40",
                    Tags = new List<string> { "青蓝", "冷静", "专业", "暗黑", "商务" }
                },
                new PresetTheme
                {
                    Name = "暗金奢华",
                    Description = "高贵典雅的金色暗黑主题",
                    BaseTheme = "Dark",
                    PrimaryColor = "#FF8F00",
                    SecondaryColor = "#9C27B0",
                    AccentColor = "#E65100",
                    Tags = new List<string> { "金色", "奢华", "高贵", "暗黑", "典雅" }
                }
            };
        }

        /// <summary>
        /// 获取暗黑主题列表
        /// </summary>
        public List<PresetTheme> GetDarkThemes()
        {
            return GetPresetThemes().Where(t => t.BaseTheme == "Dark").ToList();
        }

        /// <summary>
        /// 获取浅色主题列表
        /// </summary>
        public List<PresetTheme> GetLightThemes()
        {
            return GetPresetThemes().Where(t => t.BaseTheme == "Light").ToList();
        }

        /// <summary>
        /// 根据标签搜索主题
        /// </summary>
        public List<PresetTheme> SearchThemesByTag(string tag)
        {
            return GetPresetThemes()
                .Where(t => t.Tags.Any(tagItem => tagItem.Contains(tag, StringComparison.OrdinalIgnoreCase)))
                .ToList();
        }

        /// <summary>
        /// 获取推荐的暗黑主题（护眼主题）
        /// </summary>
        public List<PresetTheme> GetRecommendedDarkThemes()
        {
            var eyeCareThemes = new[] { "经典暗黑", "森林暗绿", "深海蓝调", "极夜青蓝" };
            return GetDarkThemes()
                .Where(t => eyeCareThemes.Contains(t.Name))
                .ToList();
        }

        /// <summary>
        /// 重置为默认主题
        /// </summary>
        public async Task ResetToDefaultAsync()
        {
            var defaultTheme = new ThemeConfig
            {
                BaseTheme = "Light",
                PrimaryColor = "#2196F3", // 浅蓝色
                SecondaryColor = "#03DAC6",
                AccentColor = "#1976D2"
            };

            await ApplyThemeAsync(defaultTheme);
        }

        /// <summary>
        /// 从配置文件加载主题
        /// </summary>
        public async Task LoadThemeFromConfigAsync()
        {
            try
            {
                var themeConfig = new ThemeConfig
                {
                    BaseTheme = _configuration["Theme:BaseTheme"] ?? "Light",
                    PrimaryColor = _configuration["Theme:PrimaryColor"] ?? "#2196F3",
                    SecondaryColor = _configuration["Theme:SecondaryColor"] ?? "#03DAC6",
                    AccentColor = _configuration["Theme:AccentColor"] ?? "#1976D2"
                };

                await ApplyThemeAsync(themeConfig);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "从配置加载主题时发生错误，使用默认主题");
                await ResetToDefaultAsync();
            }
        }

        /// <summary>
        /// 保存主题配置
        /// </summary>
        private async Task SaveThemeConfigAsync(ThemeConfig themeConfig)
        {
            try
            {
                // 这里可以实现保存到配置文件的逻辑
                // 由于IConfiguration通常是只读的，这里只记录日志
                _logger.LogInformation("主题配置已更新（注意：需要实现持久化存储）");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存主题配置时发生错误");
            }
        }

        /// <summary>
        /// 颜色转换为十六进制字符串
        /// </summary>
        private string ColorToHex(Color color)
        {
            return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
        }

        /// <summary>
        /// 十六进制字符串转换为颜色
        /// </summary>
        private Color HexToColor(string hex)
        {
            if (string.IsNullOrEmpty(hex) || !hex.StartsWith("#"))
                return Colors.Blue;

            try
            {
                return (Color)ColorConverter.ConvertFromString(hex);
            }
            catch
            {
                return Colors.Blue;
            }
        }
    }

    /// <summary>
    /// 主题变更事件参数
    /// </summary>
    public class ThemeChangedEventArgs : EventArgs
    {
        public ThemeConfig NewTheme { get; }

        public ThemeChangedEventArgs(ThemeConfig newTheme)
        {
            NewTheme = newTheme;
        }
    }
}
